package com.csp.main.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csp.common.utils.R;
import com.csp.main.entity.UserCommon;
import com.csp.main.entity.vo.UserLogin;
import com.csp.main.entity.vo.UserMail;
import com.csp.main.entity.vo.UserRegister;
import com.csp.main.service.UserCommonService;
import com.csp.main.utils.GetVerCode;
import com.csp.main.utils.JWTUtils;
import com.csp.main.utils.MailClient;
import com.csp.main.utils.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Classname UserCommonController
 * @Description done
 * @Date 2022/6/4 20:34
 * @Created by csp
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserCommonController {

    @Autowired
    private UserCommonService userCommonService;
    @Autowired
    private MailClient mailClient;
    @Autowired
    private RedisUtil redisUtil;

    private static final String RESPONSE_KEY = "message";

    @PostMapping("/user_login")
    public R login( HttpServletResponse response, @RequestBody UserLogin userLogin){
        //判断是否合法
        String mail = userLogin.getMail();
        String password = userLogin.getPassword();
        if(!StringUtils.isNotEmpty(mail)&&StringUtils.isNotEmpty(password)){
            return R.error().data(RESPONSE_KEY,"账号或者密码格式错误");
        }
        //判断是否注册
        QueryWrapper<UserCommon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mail",mail);
        List<UserCommon> list = userCommonService.list(queryWrapper);
        if(list.size() == 0){
            return R.error().data(RESPONSE_KEY,"未注册");
        }
        UserCommon userCommon1 = list.get(0);
        if(userCommon1.getPassword().equals(password)){
            String id = userCommon1.getId();
            String token = JWTUtils.createToken(id);
            response.setHeader(JWTUtils.USER_LOGIN_TOKEN,token);
            return R.ok().data(RESPONSE_KEY,"登录成功").data("token",token);
        }else{
            return R.error().data(RESPONSE_KEY,"账号或密码错误");
        }
    }

    @PostMapping("/send_mail")
    public R sendMail(@RequestBody UserMail userMail){
        String mail = userMail.getMail();
        //判断是否合法
        if(!StringUtils.isNotEmpty(mail)){
            return R.error();
        }
        System.out.println(mail);
        return mailClient.sendMail(mail)?R.ok():R.error();
    }

    @PostMapping("/user_login_mail")
    public R loginByMail(HttpServletResponse response, @RequestBody UserMail userMail){
        //TODO

        String mail = userMail.getMail();
        String code = userMail.getCode();

        if(!StringUtils.isNotEmpty(mail) || !StringUtils.isNotEmpty(code)){
            return R.error();
        }
        //判断验证码是否正确
        String code_redis =(String) redisUtil.get(mail);
        System.out.println(code_redis);
        if(!code.equals(code_redis)){
            return R.error().data(RESPONSE_KEY,"验证码错误");
        }

        //判断是否注册
        QueryWrapper<UserCommon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mail",mail);
        List<UserCommon> list = userCommonService.list(queryWrapper);
        if(list.size() == 0){
            return R.error().data(RESPONSE_KEY,"未注册");
        }

        //删掉验证码
        redisUtil.del(mail);

        //返回token
        UserCommon userCommon1 = list.get(0);
        String id = userCommon1.getId();
        String token = JWTUtils.createToken(id);
        response.setHeader(JWTUtils.USER_LOGIN_TOKEN,token);
        return R.ok().data(RESPONSE_KEY,"登录成功").data("token",token);
    }

    @GetMapping("/user_info")
    public R getUserInfo(HttpServletRequest request){
        //获取token识别用户ID
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        //查数据库
        UserCommon userCommon = userCommonService.getById(userId);
        return R.ok().data("rows",userCommon);
    }

    @PostMapping("/user_register")
    public R register(@RequestBody UserRegister userRegister){
        String name = userRegister.getName();
        String mail = userRegister.getMail();
        String password = userRegister.getPassword();
        String avatar = userRegister.getAvatar();
        String code = userRegister.getCode();

        if(!StringUtils.isNotEmpty(mail) || !StringUtils.isNotEmpty(name)||!StringUtils.isNotEmpty(password)||!StringUtils.isNotEmpty(avatar)){
            return R.error().data(RESPONSE_KEY,"字段不能为空");
        }
        //判断是否注册
        QueryWrapper<UserCommon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mail",mail);
        List<UserCommon> list = userCommonService.list(queryWrapper);
        if(list.size() != 0){
            return R.error().data(RESPONSE_KEY,"已经注册");
        }

        String code_redis =(String) redisUtil.get(mail);
        if(!code.equals(code_redis)){
            System.out.println(redisUtil.get(mail));
            return R.error().data(RESPONSE_KEY,"验证码错误");
        }

        redisUtil.del(mail);
        UserCommon userCommon = new UserCommon();
        userCommon.setName(name);
        userCommon.setPassword(password);
        userCommon.setAvatar(avatar);
        userCommon.setMail(mail);
        userCommonService.save(userCommon);
        return R.ok().data(RESPONSE_KEY,"注册成功");
    }

    @GetMapping("get_by_id/{id}")
    public R getById(@PathVariable String id){
        UserCommon userCommonServiceById = userCommonService.getById(id);
        return R.ok().data("user",userCommonServiceById);
    }

    @PutMapping("update")
    public R update(@RequestBody UserCommon userCommon){
        boolean b = userCommonService.updateById(userCommon);
        return b?R.ok():R.error();
    }
}
